package org.miaosha.service;

import org.miaosha.mapper.GoodsInfoViewMapper;
import org.miaosha.mapper.GoodsMapper;
import org.miaosha.mapper.MiaoshaGoodsMapper;
import org.miaosha.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author Wrb
 * @date 2019/7/26 14:26
 */
@Service
public class GoodsService {

	@Autowired
	private GoodsMapper goodsMapper;

	@Autowired
	private GoodsInfoViewMapper goodsInfoViewMapper;

	@Autowired
	private MiaoshaGoodsMapper miaoshaGoodsMapper;

	public List<GoodsInfoView> getGoodsInfoList() {
		return goodsInfoViewMapper.selectByExample(new GoodsInfoViewCriteria());
	}

	public GoodsInfoView getGoodsInfoById(Long id) {
		GoodsInfoViewCriteria criteria = new GoodsInfoViewCriteria();
		criteria.or().andIdEqualTo(id);
		List<GoodsInfoView> goodsInfoViews = goodsInfoViewMapper.selectByExample(criteria);
		if (CollectionUtils.isEmpty(goodsInfoViews)) {
			return null;
		}
		return goodsInfoViews.get(0);
	}

	public int reduceStock(GoodsInfoView goods) {
		MiaoshaGoods g = new MiaoshaGoods();
		g.setStockCount(goods.getStockCount() - 1);
		MiaoshaGoodsCriteria criteria = new MiaoshaGoodsCriteria();
		criteria.or().andGoodsIdEqualTo(goods.getId());
		return miaoshaGoodsMapper.updateByExampleSelective(g, criteria);
	}
}
